package com.example.recognize.config;

import com.example.recognize.model.Hr;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * spring-security
 * 登录拦截器，校验验证码和登录用户信息
 */
public class LoginFilter extends UsernamePasswordAuthenticationFilter{
    @Autowired
    SessionRegistry sessionRegistry;
        public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response){
            //判断请求类型
            if (!request.getMethod().equals("POST")){
                throw new AuthenticationServiceException(
                        "Authentication method not supported: " + request.getMethod()
                );
            }
            //获取验证码
            String verify_code = (String) request.getSession().getAttribute("verify_code");
            //判断请求是否为json格式
            if (request.getContentType().contains(MediaType.APPLICATION_JSON_VALUE) || request.getContentType().contains(MediaType.APPLICATION_JSON_UTF8_VALUE)){
                Map<String, String> loginData = new HashMap<>();
                try {
                    //从HTTP请求的输入流中反序列化JSON数据，并将其转换为一个Map对象
                    loginData = new ObjectMapper().readValue(request.getInputStream(), Map.class);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }finally {
                    String code = loginData.get("code");
                    //判断验证码是否正确
                    checkCode(response,code,verify_code);
                }
                String username = loginData.get(getUsernameParameter());
                String password = loginData.get(getPasswordParameter());
                if (username == null){
                    username = "";
                }
                if (password == null){
                    password = "";
                }
                username = username.trim();
                UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);
                //将request的信息复制到authRequest中
                setDetails(request,authRequest);
                Hr principal = new Hr();
                principal.setUsername(username);
                sessionRegistry.registerNewSession(request.getSession(true).getId(),principal);
                return this.getAuthenticationManager().authenticate(authRequest);
            }else {
                checkCode(response,request.getParameter("code"),verify_code);
                return super.attemptAuthentication(request,response);
            }
        }

    private void checkCode(HttpServletResponse response, String code, String verifyCode) {
            if (code == null || verifyCode == null || "".equals(code) || !verifyCode.toLowerCase().equals(code.toLowerCase())){
                throw new AuthenticationServiceException("验证码不正确");
            }
    }

}
